package com.scisoft.scan.control.depot;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import androidx.swiperefreshlayout.widget.CircularProgressDrawable;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.nlscan.android.scan.ScanManager;
import com.scisoft.scan.control.ClearEditText;
import com.scisoft.scan.control.ScanHelper;
import com.scisoft.scan.data.BarCodeBean;
import com.scisoft.scan.data.PartBean;
import com.scisoft.scan.data.depot.AreaBean;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.control.MainMenuActivity;
import com.scisoft.scan.data.depot.DepotOrderBean;
import com.scisoft.scan.data.depot.DepotOrderStatis;
import com.scisoft.scan.data.depot.WarehouseBean;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.WebServiceHelper;
import com.scisoft.scan.ws.WebServiceHelper_Depot;

import java.util.ArrayList;
import java.util.List;

public class DepotInfoActivity extends Activity {

    private String TAG = "bugcao-scan";


    private boolean isDataInitialized = false; // 是否是初次加载

    private ImageView iv_Back; //返回按钮
    private ImageView iv_query; //搜索按钮

    private Spinner spin_1;//出库入库
    private Spinner spin_2;//仓库
    private Spinner spin_3;//库区
    private Spinner spin_4;//单据业务类型
    private SwipeRefreshLayout mRefreshLayout;
    private ListView lv_data;
    private TextView bt_all;
    private TextView bt_undo;
    private TextView bt_doing;
    private TextView bt_done;
    private View v_all;
    private View v_undo;
    private View v_doing;
    private View v_done;
    private ClearEditText et_bar;
    private String bizId;// 1 全部 2 未处理 3 处理中 4 已完成
    //全部的订单
    private List<DepotOrderBean> depotOrderBeanList;
    //当前过滤后的订单，列表操作的是这个
    private List<DepotOrderBean> filterDepotOrderBeanList;
    private DepotOrderStatis depotOrderStatis;
    private List<String> orderTypeList;
    private List<String> depotList = new ArrayList<>();
    private List<WarehouseBean> depotBeanList = new ArrayList<WarehouseBean>();
    private List<String> areaList = new ArrayList<>();//库区字典
    private List<AreaBean> areaBeanList = new ArrayList<>();//库区字典
    private List<String> orderTypeNameList = new ArrayList<>();//单据业务类型字典
    private String selectedOrderType = "全部作业";//出仓 入仓
    private String selectedOrderTypeName = "全部";//单据作业类型
    private int selectedDepotNo = 0;
    private int selectedAreaNo = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//即隐藏标题栏
        setContentView(R.layout.activity_depot_info);

        //初始化扫码
        init();

        //下拉刷新控件
        mRefreshLayout = findViewById(R.id.swipe_layout);
        mRefreshLayout.setProgressViewEndTarget(true, 100);
        mRefreshLayout.setSize(CircularProgressDrawable.DEFAULT);
        mRefreshLayout.setColorSchemeColors(Color.BLACK, Color.GREEN, Color.RED, Color.YELLOW, Color.BLUE);
        mRefreshLayout.setColorSchemeResources(R.color.blue, R.color.red, R.color.green);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mRefreshLayout.setRefreshing(false);
                QueryDepotOrder(false);
            }
        });
        //控件初始化
        lv_data = findViewById(R.id.lv_data);
        lv_data.setOnItemClickListener(new ListViewClick());
        bt_all = findViewById(R.id.bt_all);
        bt_undo = findViewById(R.id.bt_undo);
        bt_doing = findViewById(R.id.bt_doing);
        bt_done = findViewById(R.id.bt_done);
        v_all = findViewById(R.id.v_all);
        v_undo = findViewById(R.id.v_undo);
        v_doing = findViewById(R.id.v_doing);
        v_done = findViewById(R.id.v_done);
        et_bar = findViewById(R.id.et_bar);
        et_bar.setText("");
        spin_1 = findViewById(R.id.spin_1);
        spin_2 = findViewById(R.id.spin_2);
        spin_3 = findViewById(R.id.spin_3);
        spin_4 = findViewById(R.id.spin_4);

        //返回
        iv_Back = findViewById(R.id.iv_back);
        iv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Intent intent = new Intent(DepotInfoActivity.this, MainMenuActivity.class);
                //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                //startActivity(intent);
                finish();
            }
        });
        //搜索框
        iv_query = findViewById(R.id.iv_query);
        iv_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                filterData(et_bar.getUpperText().toString());
                BindData(DepotInfoActivity.this);
            }
        });
        //下拉列表
        setSpin();
        //页签切换
        bt_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButton(v);
            }
        });
        bt_undo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButton(v);
            }
        });
        bt_doing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButton(v);
            }
        });
        bt_done.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButton(v);
            }
        });

    }

    //设置下拉列表
    private void setSpin() {
        //下拉框：操作类型
        orderTypeList = new ArrayList<>();
        orderTypeList.add("全部作业");
        orderTypeList.add("入仓");
        orderTypeList.add("出仓");

        spin_4.setVisibility(View.VISIBLE);
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, R.layout.style_spinner, orderTypeList);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin_1.setAdapter(adapter1);
        spin_1.setSelection(2, true);
        selectedOrderType = "出仓";
        spin_1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedOrderType = orderTypeList.get(position);
                //入仓时增加过滤条件
                if ("出仓".equals(selectedOrderType)) {
                    spin_4.setVisibility(View.VISIBLE);
                } else {
                    spin_4.setVisibility(View.GONE);
                }
                QueryDepotOrder(false);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        //下拉框： 仓库、库区列表、作业单据类型
        QueryWarehouse();

    }

    //设置tab页的颜色
    private void setButton(View v) {
        if (v.getId() == bt_all.getId()) {
            bizId = "1";//全部
            v_all.setVisibility(View.VISIBLE);
            v_undo.setVisibility(View.INVISIBLE);
            v_doing.setVisibility(View.INVISIBLE);
            v_done.setVisibility(View.INVISIBLE);
            bt_all.setTextColor(getResources().getColor(R.color.tab_text_color_select));
            bt_undo.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_doing.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_done.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
        } else if (v.getId() == bt_undo.getId()) {
            bizId = "2";//未处理
            v_all.setVisibility(View.INVISIBLE);
            v_undo.setVisibility(View.VISIBLE);
            v_doing.setVisibility(View.INVISIBLE);
            v_done.setVisibility(View.INVISIBLE);
            bt_all.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_undo.setTextColor(getResources().getColor(R.color.tab_text_color_select));
            bt_doing.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_done.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
        } else if (v.getId() == bt_doing.getId()) {
            bizId = "3";//处理中
            v_all.setVisibility(View.INVISIBLE);
            v_undo.setVisibility(View.INVISIBLE);
            v_doing.setVisibility(View.VISIBLE);
            v_done.setVisibility(View.INVISIBLE);
            bt_all.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_undo.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_doing.setTextColor(getResources().getColor(R.color.tab_text_color_select));
            bt_done.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
        } else {
            bizId = "4";//已完成
            v_all.setVisibility(View.INVISIBLE);
            v_undo.setVisibility(View.INVISIBLE);
            v_doing.setVisibility(View.INVISIBLE);
            v_done.setVisibility(View.VISIBLE);
            bt_all.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_undo.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_doing.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_done.setTextColor(getResources().getColor(R.color.tab_text_color_select));
        }
        QueryDepotOrder(false);
    }

    //进入二级界面
    private class ListViewClick implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(DepotInfoActivity.this, DepotDetailActivity.class);
            if (position >= 0 && position < filterDepotOrderBeanList.size()) {
                DepotOrderBean depotOrderBean = filterDepotOrderBeanList.get(position);
                intent.putExtra("data", depotOrderBean);
                startActivityForResult(intent, 0);
            }
        }
    }

    //返回当前界面
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //只有在订单提交的时候才刷新，否则只是返回上一个界面
        if (resultCode == RESULT_OK) {
            switch (bizId) {
                case "1":
                    setButton(bt_all);
                    break;
                case "2":
                    setButton(bt_undo);
                    break;
                case "3":
                    setButton(bt_doing);
                    break;
                case "4":
                    setButton(bt_done);
                    break;
            }
        }
    }

    //查询订单
    private void QueryDepotOrder(boolean depotChanged) {
        CommonUtil.showPress(DepotInfoActivity.this);
        QueryDepotOrderTask QueryPackInfoTask = new QueryDepotOrderTask(DepotInfoActivity.this, depotChanged);
        QueryPackInfoTask.execute();
    }

    //过滤(配件列表包含过滤条件)
    private void filterData(String filter) {
        filterDepotOrderBeanList = new ArrayList<>();
        if (filter != null && filter != "") {
            if (depotOrderBeanList != null) {
                for (int i = 0; i < depotOrderBeanList.size(); i++) {
                    DepotOrderBean bean = depotOrderBeanList.get(i);
                    if (bean.orderNo.contains(filter) || bean.supplierName.contains(filter) || bean.no.contains(filter)) {
                        filterDepotOrderBeanList.add(bean);
                    }
                }
            }
        } else {
            if (depotOrderBeanList != null) {
                for (int i = 0; i < depotOrderBeanList.size(); i++) {
                    DepotOrderBean bean = depotOrderBeanList.get(i);
                    filterDepotOrderBeanList.add(bean);
                }
            }
        }
    }

    //查询订单服务
    class QueryDepotOrderTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        boolean mdepotChanged = false;

        QueryDepotOrderTask(Context context, boolean depotChanged) {
            super();
            mcontext = context;
            mdepotChanged = depotChanged;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                if (depotBeanList != null && selectedDepotNo >= 0 && selectedDepotNo < depotBeanList.size()) {
                    //仓库发生变化，获取也需要变化
                    if (mdepotChanged) {
                        areaBeanList = WebServiceHelper_Depot.DEPOT_12(depotBeanList.get(selectedDepotNo).depotId);
                        selectedAreaNo = 0;
                    }
                    if (areaBeanList != null && selectedAreaNo >= 0 && selectedAreaNo < areaBeanList.size()) {
                        //查询各tab页面数量
                        depotOrderStatis = WebServiceHelper_Depot.DEPOT_07(selectedOrderType, depotBeanList.get(selectedDepotNo).depotId, areaBeanList.get(selectedAreaNo).areaId, selectedOrderTypeName);
                        //查询列表数据
                        depotOrderBeanList = WebServiceHelper_Depot.DEPOT_02(bizId, selectedOrderType, depotBeanList.get(selectedDepotNo).depotId, areaBeanList.get(selectedAreaNo).areaId, selectedOrderTypeName);
                    }

                }
                msg = "成功";

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                filterData(et_bar.getUpperText().toString());
                BindData(mcontext);
                if (mdepotChanged) {
                    SetSpanArea(mcontext);
                }
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //绑定订单数据
    private void BindData(Context context) {
        //标题
        bt_all.setText("全部[" + depotOrderStatis.allOrderCount + "]");
        bt_undo.setText("未处理[" + depotOrderStatis.undoOrderCount + "]");
        bt_doing.setText("处理中[" + depotOrderStatis.doingOrderCount + "]");
        bt_done.setText("已完成[" + depotOrderStatis.doneOrderCount + "]");
        //数据
        DepotInfoAdapter adapter = new DepotInfoAdapter(filterDepotOrderBeanList, context);
        lv_data.setAdapter(adapter);
    }

    //查询仓库
    private void QueryWarehouse() {
        QueryWarehouseTask queryWarehouseTask = new QueryWarehouseTask(DepotInfoActivity.this);
        queryWarehouseTask.execute();
    }

    //查询仓库服务
    class QueryWarehouseTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        QueryWarehouseTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //初始化仓库
                depotBeanList = WebServiceHelper_Depot.DEPOT_01();
                //初始化库区
                if (depotBeanList.size() > 0) {
                    areaBeanList = WebServiceHelper_Depot.DEPOT_12(depotBeanList.get(0).depotId);
                }
                //初始化业务类型
                orderTypeNameList = WebServiceHelper_Depot.DEPOT_15();

                msg = "成功";

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            if (msg.contains("成功")) {
                SetWarehouse(mcontext);
                SetSpanArea(mcontext);
                SetOrderTypeName(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    ///绑定仓库列表的下拉框
    private void SetWarehouse(Context context) {
        depotList.clear();
        for (int i = 0; i < depotBeanList.size(); i++) {
            depotList.add(depotBeanList.get(i).depotName);
        }

        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, R.layout.style_spinner, depotList);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin_2.setAdapter(adapter2);
        spin_2.setSelection(0, true);
        spin_2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedDepotNo = position;
                QueryDepotOrder(true);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        //查询
        setButton(bt_undo);//默认显示未处理
    }

    //绑定货位数据
    private void SetSpanArea(Context context) {

        areaList.clear();
        for (int i = 0; i < areaBeanList.size(); i++) {
            areaList.add(areaBeanList.get(i).areaName);
        }
        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, R.layout.style_spinner, areaList);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin_3.setAdapter(adapter2);
        spin_3.setSelection(0, true);
        spin_3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedAreaNo = position;
                QueryDepotOrder(false);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    //绑定业务类型
    private void SetOrderTypeName(Context context) {
        ArrayAdapter<String> adapter4 = new ArrayAdapter<String>(this, R.layout.style_spinner, orderTypeNameList);
        adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin_4.setAdapter(adapter4);
        if (orderTypeNameList != null && orderTypeNameList.size() > 0) {
            spin_4.setSelection(0, true);
            selectedOrderTypeName = orderTypeNameList.get(0);
        }
        spin_4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedOrderTypeName = orderTypeNameList.get(position);
                QueryDepotOrder(false);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    //region 以下为扫码相关

    //初始化
    private void init() {
        //初始化Profile
        ScanHelper.CreateProfile(this);
        //设置广播消息的接收器
        registerReceiver();
    }

    //查询条码服务
    class QueryBarCodeTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private String barCode;
        private BarCodeBean barCodeBean = null;
        private DepotOrderBean depotOrderBean = null;
        private PartBean partBean = null;

        QueryBarCodeTask(Context context, String barCode) {
            super();
            mcontext = context;
            this.barCode = barCode;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                barCodeBean = WebServiceHelper.ParseBarCode(barCode);
                if (barCodeBean.barType == BarCodeBean.BAR_PART) {
                    partBean = barCodeBean.partBean;
                    if (partBean == null) {
                        msg = "无效配件条码";
                        return msg;
                    } else {
                        depotOrderBean = WebServiceHelper_Depot.DEPOT_14(partBean.partCode);
                    }
                } else {
                    msg = "无效配件条码";
                    return msg;
                }
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                if (depotOrderBean != null) {
                    Intent intent = new Intent(DepotInfoActivity.this, DepotDetailActivity.class);
                    intent.putExtra("data", depotOrderBean);
                    intent.putExtra("part", partBean);
                    startActivityForResult(intent, 0);
                } else {
                    Toast.makeText(getApplicationContext(), "未查询到包含此配件的订单", Toast.LENGTH_LONG).show();
                }

            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //扫码处理
    private void ScanData(String barCode) throws Exception {
        if (barCode != null && barCode.length() > 0) {
            CommonUtil.showPress(this);
            QueryBarCodeTask queryBarCodeTask = new QueryBarCodeTask(DepotInfoActivity.this, barCode);
            queryBarCodeTask.execute();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unRegisterReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
    }

    //注册广播
    private void registerReceiver() {
        IntentFilter intFilter = new IntentFilter(ScanManager.ACTION_SEND_SCAN_RESULT);
        registerReceiver(mResultReceiver, intFilter);
//        IntentFilter filter = new IntentFilter();
//        filter.addAction(ScanHelper.ACTION_RESULT_NOTIFICATION);   // for notification result
//        filter.addAction(ScanHelper.ACTION_RESULT);                // for error code result
//        filter.addCategory(Intent.CATEGORY_DEFAULT);    // needed to get version info
//        filter.addAction(ScanHelper.ACTION_SCAN_OUTPUT); // register to received broadcasts via DataWedge scanning
//        registerReceiver(mResultReceiver, filter);
    }

    //取消注册广播
    private void unRegisterReceiver() {
        try {
            unregisterReceiver(mResultReceiver);
        } catch (Exception e) {
            Toast.makeText(this, "注销扫码失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    //监听扫码数据的广播，当设置广播输出时作用该方法获取扫码数据
    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ScanHelper.ACTION_SCAN_OUTPUT)) {
                // 处理扫码结果
                try {
                    String decodedData = intent.getStringExtra("com.symbol.datawedge.data_string");
                    Log.d(TAG, String.format("监听扫码结果%s", decodedData));
                    et_bar.setText(decodedData);
                    ScanData(decodedData);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(DepotInfoActivity.this, "扫描失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    };
    //endregion
}
